import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * Jackson转换工具类
 *
 * @author fuyuda
 */
public class MyJsonUtils {

    private MyJsonUtils() {
    }

    /**
     * json转任何格式
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(MyJsonUtils.class);

    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static String toJsonStr(Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof String) {
            return object.toString();
        }
        try {
            return MAPPER.writeValueAsString(object);
        } catch (IOException e) {
            logger.error("对象转json出错: ", e);
            return null;
        }
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }
}
